"use client"

import { View, Text, TouchableOpacity, StyleSheet, ScrollView } from "react-native"
import { Volume2, Film, BookOpen } from "lucide-react-native"
import { theme } from "../../constants/theme"

interface PhoneticPart {
    text: string
    isHighlighted: boolean
}

// Split phonetic text to match syllables
function splitPhonetic(phonetic: string, syllableCount: number): PhoneticPart[] {
    // Remove the first and last brackets
    const cleanPhonetic = phonetic.replace(/^\[|\]$/g, "")

    // Simple split strategy - divide the phonetic text into roughly equal parts
    const parts = cleanPhonetic.split(/(?=[ˈˌ])/).filter(Boolean)

    // Match parts count with syllables count
    const result: PhoneticPart[] = []
    const partsPerSyllable = Math.ceil(parts.length / syllableCount)

    let currentIndex = 0
    for (let i = 0; i < syllableCount; i++) {
        const currentParts = parts.slice(currentIndex, currentIndex + partsPerSyllable)
        result.push({
            text: currentParts.join(""),
            isHighlighted: i % 2 === 1, // Alternate highlighting
        })
        currentIndex += partsPerSyllable
    }

    return result
}

interface SyllableSplittingProps {
    word: {
        id: string
        word: string
        phonetic: string
        type: string
        meanings: string[]
        syllables: string[]
        phoneticSyllables: string[]
    }
    isPlayingPart: string | null
    selectedPhonetic: number | null
    isSplit: boolean
    settings: {
        translationFontSize: number
    }
    onPlayAudio: (text: string, duration?: number) => Promise<void>
    onSyllablePress: (syllable: string, index: number) => void
    onPhoneticPress: (phonetic: string, index: number) => void
    onVideoPress: () => void
    DetailPress: () => void
}

export function SyllableSplitting({
    word,
    isPlayingPart,
    selectedPhonetic,
    isSplit,
    settings,
    onPlayAudio,
    onSyllablePress,
    onPhoneticPress,
    onVideoPress,
    DetailPress,
}: SyllableSplittingProps) {
    // 渲染单词部分
    const renderWord = () => {
        if (!isSplit) {
            return <Text style={styles.syllable}>{word.word}</Text>
        }

        return word.syllables.map((syllable, index) => (
            <TouchableOpacity key={index} onPress={() => onSyllablePress(syllable, index)} activeOpacity={0.6}>
                <Text
                    style={[
                        styles.syllable,
                        index % 2 === 1 && { color: theme.colors.primary.default },
                        isPlayingPart === syllable && styles.playingPart,
                    ]}
                >
                    {syllable}
                </Text>
            </TouchableOpacity>
        ))
    }

    // 渲染音标部分
    const renderPhonetic = () => {
        if (!isSplit) {
            return <Text style={styles.phonetic}>{word.phonetic}</Text>
        }

        const phoneticParts = splitPhonetic(word.phonetic, word.syllables.length)

        return (
            <View style={styles.splitPhoneticContainer}>
                {phoneticParts.map((part, index) => (
                    <Text key={index} style={[styles.phoneticPart, part.isHighlighted && styles.phoneticPartHighlighted]}>
                        {index === 0 ? "[" : ""}
                        {part.text}
                        {index === phoneticParts.length - 1 ? "]" : "•"}
                    </Text>
                ))}
            </View>
        )
    }

    // 处理详解按钮点击
    // const handleDetailPress = () => {
    //     console.log("详解按钮点击 - 单词:", word.word)
    //     // 这里可以添加详解功能的实现
    // }

    // 修改renderMeanings函数，确保词性和翻译在同一行显示
    const renderMeanings = () => {
        if (!word.meanings || word.meanings.length === 0) return null

        return (
            <View style={styles.meaningRow}>
                <View style={styles.meaningContainer}>
                    {word.meanings.map((meaning, index) => (
                        <Text key={index} style={[styles.meaning, { fontSize: settings.translationFontSize }]}>
                            <Text style={styles.type}>{word.type} </Text>
                            {meaning}
                        </Text>
                    ))}
                </View>
                <TouchableOpacity style={styles.detailButton} onPress={DetailPress}>
                    <BookOpen size={16} color={theme.colors.primary.default} />
                </TouchableOpacity>
            </View>
        )
    }

    return (
        <>
            {/* 单词部分 */}
            <View style={styles.wordBackground}>
                <View style={styles.wordSplitContainer}>{renderWord()}</View>
            </View>

            {/* 音标部分 */}
            <View style={styles.phoneticBackground}>
                <View style={styles.phoneticContainer}>
                    {renderPhonetic()}
                    <TouchableOpacity
                        style={styles.audioButton}
                        onPress={() => onPlayAudio(word.word)}
                        disabled={isPlayingPart !== null}
                    >
                        <Volume2 size={20} color={isPlayingPart ? theme.colors.primary.light : theme.colors.primary.default} />
                    </TouchableOpacity>
                </View>
            </View>

            {/* 词义部分 */}
            <View style={styles.meaningsContainer}>{renderMeanings()}</View>

            {/* 音标拆分部分 */}
            <View style={styles.phoneticSyllablesContainer}>
                <View style={styles.phoneticButtonsRow}>
                    <View style={styles.phoneticScrollContainer}>
                        <ScrollView
                            horizontal
                            showsHorizontalScrollIndicator={false}
                            contentContainerStyle={styles.phoneticButtonsScrollContent}
                        >
                            {word.phoneticSyllables.map((phonetic, index) => (
                                <TouchableOpacity
                                    key={index}
                                    style={[
                                        styles.phoneticButton,
                                        selectedPhonetic === index && styles.phoneticButtonSelected,
                                        isPlayingPart === phonetic && styles.playingPhonetic,
                                    ]}
                                    onPress={() => onPhoneticPress(phonetic, index)}
                                    disabled={isPlayingPart !== null}
                                >
                                    <Text
                                        style={[styles.phoneticButtonText, selectedPhonetic === index && styles.phoneticButtonTextSelected]}
                                    >
                                        {phonetic}
                                    </Text>
                                </TouchableOpacity>
                            ))}
                        </ScrollView>
                    </View>

                    <TouchableOpacity style={styles.videoButton} onPress={onVideoPress}>
                        {selectedPhonetic !== null && (
                            <Text style={styles.currentPhoneticText}>{word.phoneticSyllables[selectedPhonetic]}</Text>
                        )}
                        <Film size={16} color={theme.colors.neutral.gray} />
                    </TouchableOpacity>
                </View>
            </View>
        </>
    )
}

// 在styles对象中添加typeContainer样式
const styles = StyleSheet.create({
    // 单词背景
    wordBackground: {
        backgroundColor: "rgba(91, 142, 244, 0.1)",
        borderRadius: theme.borderRadius.large,
        paddingVertical: theme.spacing.lg,
        marginBottom: theme.spacing.md,
        alignItems: "center",
    },
    wordSplitContainer: {
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
    },
    // 音标背景
    phoneticBackground: {
        backgroundColor: "rgba(255, 149, 0, 0.1)",
        borderRadius: theme.borderRadius.medium,
        paddingVertical: theme.spacing.xs,
        paddingHorizontal: theme.spacing.sm,
        marginBottom: theme.spacing.lg,
        alignSelf: "center",
    },
    phoneticContainer: {
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
    },
    phonetic: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.gray,
        marginRight: theme.spacing.sm,
    },
    audioButton: {
        padding: theme.spacing.xs,
    },
    // 更新词义容器样式
    meaningsContainer: {
        alignItems: "center",
        marginBottom: theme.spacing.md,
        width: "100%",
    },
    meaningRow: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        marginBottom: theme.spacing.xs,
        maxWidth: "90%",
    },
    meaningContainer: {
        flex: 1,
        alignItems: "center",
    },
    meaning: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.black,
        textAlign: "center",
    },
    type: {
        fontSize: theme.fontSize.md,
        color: theme.colors.primary.default,
        fontWeight: theme.fontWeight.semiBold,
    },
    detailButton: {
        width: 32,
        height: 32,
        borderRadius: 16,
        backgroundColor: "rgba(91, 142, 244, 0.1)",
        alignItems: "center",
        justifyContent: "center",
        marginLeft: theme.spacing.sm,
    },
    phoneticSyllablesContainer: {
        alignItems: "center",
        marginVertical: theme.spacing.md,
        width: "100%",
    },
    phoneticButtonsRow: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        width: "100%",
        maxWidth: "90%",
    },
    phoneticScrollContainer: {
        maxWidth: "80%",
    },
    phoneticButtonsScrollContent: {
        paddingVertical: theme.spacing.xs,
        flexDirection: "row",
    },
    phoneticButton: {
        paddingHorizontal: theme.spacing.md,
        paddingVertical: theme.spacing.sm,
        backgroundColor: "rgba(91, 142, 244, 0.1)",
        borderRadius: 20,
        marginRight: theme.spacing.xs,
        width: 50,
        alignItems: "center",
    },
    phoneticButtonSelected: {
        backgroundColor: "rgba(91, 142, 244, 0.3)",
        borderWidth: 1,
        borderColor: theme.colors.primary.default,
    },
    phoneticButtonText: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.darkGray,
    },
    phoneticButtonTextSelected: {
        color: theme.colors.primary.default,
        fontWeight: theme.fontWeight.semiBold,
    },
    videoButton: {
        flexDirection: "row",
        alignItems: "center",
        paddingHorizontal: theme.spacing.md,
        paddingVertical: theme.spacing.sm,
        backgroundColor: "rgba(91, 142, 244, 0.1)",
        borderRadius: 20,
        marginLeft: theme.spacing.md,
    },
    currentPhoneticText: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.primary.default,
        marginRight: theme.spacing.sm,
    },
    playingPart: {
        opacity: 0.7,
    },
    playingPhonetic: {
        backgroundColor: `${theme.colors.primary.default}30`,
    },
    syllable: {
        fontSize: 32,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.neutral.black,
        marginHorizontal: 2,
    },
    splitPhoneticContainer: {
        flexDirection: "row",
        alignItems: "center",
        flexWrap: "wrap",
        justifyContent: "center",
    },
    phoneticPart: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.gray,
        marginHorizontal: 2,
    },
    phoneticPartHighlighted: {
        color: theme.colors.primary.default,
    },
})

